﻿using System;
using System.Collections.Generic;
using System.Linq;
using BLL.Interface.Base;
using BLL.Model.Base;

namespace BLL.Implement.Base
{
    public class LoginHelperImpl : ILoginHelper
    {
        private readonly Dictionary<string, LoginUserInfo> _userInfoList;

        public LoginHelperImpl()
        {
            _userInfoList = new Dictionary<string, LoginUserInfo>();
        }

        public bool AddLoginUser(LoginUserInfo userInfo)
        {
            if (!_userInfoList.ContainsKey(userInfo.LoginUserId))
            {
                _userInfoList.Add(userInfo.LoginUserId, userInfo);
                return true; 
            }
            return false;
        }

        public bool DeleteLoginUser(string userId)
        {
            if (_userInfoList.ContainsKey(userId))
            {
                _userInfoList.Remove(userId);
                return true;
            }
            return false;
        }

        public LoginUserInfo FindLoginUserInfo(string userId)
        {
            return _userInfoList.ContainsKey(userId) ? _userInfoList[userId] : null;
        }

        public bool CheckUserIsLogin(string accountName)
        {
            var q = _userInfoList.Count(p => p.Value.UserAccountName == accountName);
            return q > 0;
        }

        public bool Login(Func<LoginUserInfo> loginHandler, out string sessionId)
        {
            sessionId = string.Empty;
            var userInfo = loginHandler.Invoke();
            if (userInfo==null)
            {
                return false;
            }
            sessionId = userInfo.LoginUserId;
            AddLoginUser(userInfo);
            return true;
        }

        public bool LogOut(Func<LoginUserInfo> logOutHandler)
        {
            var userInfo = logOutHandler.Invoke();
            return DeleteLoginUser(userInfo.LoginUserId);
        }

    }
}